#!/bin/bash

path=$1
mocker_lib=$2

export MOCKER_LIB_PATH=$mocker_lib

declare -i shelltest_all_tests=0
declare -i shelltest_all_succ=0
declare -i shelltest_all_fail=0

for file in $path/*; do
    if [[ -f $file ]] && [[ $file == *.sh ]]; then
        echo -e "\033[1m\033[34mRunning test: $file\033[0m"
        cat << EOF > /tmp/testcase.sh
rm -f /tmp/prepare.txt

source \$MOCKER_LIB_PATH/mocker.sh
source \$MOCKER_LIB_PATH/stub.sh
source "$file"

declare -i all_tests=0
declare -i all_succ=0
declare -i all_fail=0

echo "------------------------------------------------------------------------------------"
for func in \$(declare -F | awk '{print \$3}' | grep test_); do
    echo -e "\033[1m\033[33m$file_\$func RUNNING...\033[0m"
    echo "------------------------------------------------------------------------------------"
    all_tests=\$((all_tests+1))

    prepare
    if [[ \$? -ne 0 ]]; then
        echo -e "\033[1m\\033[31m$file_\$func prepare FAILED\\033[0m"
        all_fail=\$((all_fail+1))
        echo "------------------------------------------------------------------------------------"
        continue;
    fi

    cd \$MOCKER_ROOT_DIR

    if declare -f setup > /dev/null; then setup; fi
    (\$func)
    if [[ \$? -ne 0 ]]; then
        echo -e "\033[1m$file_\$func\033[0m \\033[31mFAILED\\033[0m"
        if declare -f teardown > /dev/null; then teardown; fi
        echo "------------------------------------------------------------------------------------"
        all_fail=\$((all_fail+1))
        continue;
    fi
    if declare -f teardown > /dev/null; then teardown; fi
    echo -e "\033[1m$file_\$func\033[0m \\033[32mPASSED\\033[0m"
    echo "------------------------------------------------------------------------------------"
    all_succ=\$((all_succ+1))
done

rm -f /tmp/result.txt
# rm -rf \$MOCKER_ROOT_DIR
echo "\$all_tests \$all_succ \$all_fail" >> /tmp/result.txt
EOF
        bash /tmp/testcase.sh
        read all succ fail < /tmp/result.txt
        shelltest_all_tests=$((shelltest_all_tests+all))
        shelltest_all_succ=$((shelltest_all_succ+succ))
        shelltest_all_fail=$((shelltest_all_fail+fail))
    fi
done
echo "------------------------------------------------------------------------------------"
echo -e "\033[33mSUMMARY:\033[0m"
echo -e "\033[33mTotal tests\033[0m: \033[1m$shelltest_all_tests\033[0m"
echo -e "\033[33mTotal passed\033[0m: \033[32m$shelltest_all_succ\033[0m"
if [[ $shelltest_all_fail -ne 0 ]]; then
    echo -e "\033[33mTotal failed\033[0m: \033[31m$shelltest_all_fail\033[0m"
else
    echo -e "\033[33mTotal failed\033[0m: $shelltest_all_fail"
fi
echo "------------------------------------------------------------------------------------"
